package com.heisen.security.interceptor;

import com.heisen.base.constant.HttpConstant;
import com.heisen.base.entity.Api;
import com.heisen.base.utils.GateWayConstantUtils;
import com.heisen.base.utils.ResponseUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author sen
 * @description
 * @date 2023/12/19 14:59
 */
public class XmServerProtectInterceptor implements HandlerInterceptor {

    /**
     *  效验请求头   判断有没有走网关
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws IOException
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        // 从请求头中获取 Zuul Token
        String token = request.getHeader(GateWayConstantUtils.ZUUL_TOKEN_HEADER);
        String zuulToken = new String(Base64Utils.encode(GateWayConstantUtils.ZUUL_TOKEN_VALUE.getBytes()));
        // 校验 Zuul Token的正确性
        if (StringUtils.equals(zuulToken, token)) {
            return true;
        } else {
            ResponseUtils.makeResponse(response,MediaType.APPLICATION_JSON_UTF8_VALUE,HttpServletResponse.SC_OK,Api.fail(HttpConstant.HttpMsg.MSG_SERVICE_NO_GETAWAY));
            return false;
        }
    }
}
